<!--
增加用户
-->
<template>
  <card-page style="width: 600px;margin-left: auto;margin-right: auto;">
    <el-form
      ref="form"
      :model="form" 
      label-width="120px"
      style="width: 600px;margin: 0 auto"
    >
      <el-form-item
        prop="berthNo"
        label="床位编号"
        :rules="[{required: true, message: ' '}]"
      >
        <el-input v-model.trim="form.berthNo" :readonly="$params.isUpdate" style="width:400px;"></el-input>
      </el-form-item>
      <el-form-item
        prop="charges"
        label="床位关联费用"
        :rules="[{required: true, message: ' '}]"
      >
        <charge-type-select ref="chargeTypeSelect" :params="$params" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-check" @click="onSubmit" :loading="submitting">确定</el-button>
      </el-form-item>
    </el-form>

  </card-page>
</template>

<script>
import ChargeTypeSelect from '../ChargeTypeSelect';

export default {
  components: {
    ChargeTypeSelect
  },
  pageProps: {
    title: ({params}) => (params.isUpdate ? '修改' : '增加') + '床位'
  },
  data() {
    return {
      form: {
        roomId: null,
        berthNo: '',
        berthTypeId: 0,
        charges: null,
        ...(this.$params.isUpdate ? this.$params.berth : {})
      },
      submitting: false
    }
  },
  async mounted() {
    if (this.$params.isUpdate) {
      const berth = await this.$http.get('/api/community/berth/berthSetting/berth/get',
        {params: {id: this.$params.berth.id}});
      ['berthTypeName', 'berthCheckin'].map(k => delete berth[k]);
      this.form = berth;
      this.$refs.chargeTypeSelect.charges = await this.$http.get(
        '/api/community/bedChargeCategory/charges', {params: {ids: berth.charges}});
    }
  },
  methods: {
    onSubmit() {
      this.form.charges = this.$refs.chargeTypeSelect.getValues();
      this.$refs.form.validate(async (valid) => {
        if (!valid) return;
        this.submitting = true;
        let form = {...this.form, ...this.$params.parentInfo};
        form.charges = form.charges.map(c => c.id).join(',');
        const ret = await this.$http.post('/api/community/berth/berthSetting/berth/save', form);
        this.submitting = false;
        if (ret == 0) {
          this.$message.success('编辑床位成功');
          this.closeCurrentPage();
          this.$params.onSuccess();
        } else if (ret == 2) {
          this.$message.error('床位编号已存在');
        } else if (ret == 3) {
          this.$message.error('不能修改该床位的床位类型，因为当前有入住者');
        }
      });
    }
  }
}
</script>